package logic

import (
	"common/comCopier"
	"common/comRsa"
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"gorm.io/gorm"
	"time"

	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterUser) (resp *types.Emp, err error) {
	// todo: add your logic here and delete this line
	if req.Account == "" {
		return nil, errors.New("username is empty")
	}
	if req.Password == "" {
		return nil, errors.New("username is empty")
	}
	toString, err := utils.Base64ToString(req.Password)
	if err != nil {
		return nil, errors.New("错误 code=1")
	}
	decrypt, err := comRsa.Decrypt(toString)
	if err != nil {
		return nil, err
	}
	var (
		user = model.User{}
	)
	err = comCopier.CopyWithOption(&user, req)
	if err != nil {
		return nil, err
	}
	user.Password = decrypt
	user.IsAdmin = 0
	user.UUID = utils.GetUuid()
	db := l.svcCtx.DB
	tb := db.Table(model.TableNameUser)
	err = tb.Transaction(func(tx *gorm.DB) error {
		var oldUser model.User
		if err2 := tx.Where("account = ?", req.Account).Where("is_del = 0").Find(&oldUser).Error; err2 != nil {
			return err2
		}
		if oldUser.UUID != "" {
			return errors.New("已有账户")
		}
		t := time.Now()
		user.CreateTime = &t
		if err := tx.Create(&user).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return
}
